// 这里并不将所有魔法值在此声明为CONST，只声明可能会改的常量，方便配置
/** 静态资源地址 */
//var CONST_STATIC_URL = 'http://127.0.0.1:8080';
var CONST_STATIC_URL = '';
/** 应用服务地址 */
//var CONST_URL = 'http://127.0.0.1:8080';
var CONST_URL = '';
/** websocket服务地址 */
//var CONST_WS_URL = 'ws://127.0.0.1:8080/webSocket';
var CONST_WS_URL = 'ws://' + location.host + '/webSocket';
/** 客户端id，用于登录及刷新token时的身份验证（oauth密码模式） */
var CONST_CLIENT_ID = 'client';
/** 客户端密码 */
var CONST_CLIENT_SECRET = 'secret';
/** 距离token过期小于该时间时，刷新token */
var CONST_REFRESH_TIME = 600000;
/** 定时检测token是否需要刷新 */
var CONST_CHECK_TOKEN_TIME = 120000;
var authAxios = axios.create();

/**
 * 判断当前用户是否有该权限
 * 
 * @param authority 权限
 */
function hasAuthority(authority) {
	if(authority == undefined || authority == null || authority == '') {
		return true;
	}
	try {
		var user = JSON.parse(localStorage.getItem('user'));
		for(var i = 0; i < user.authorities.length; i++) {
			if(user.authorities[i].authority == authority) {
				return true;
			}
		}
	} catch(e) {}
	return false;
}

/**
 * 检测localStorage中的token是否有效，如果失效则刷新token
 */
function checkToken() {
	var p = Promise.resolve();
	return p.then(function(response) {
			var token = JSON.parse(localStorage.getItem('token'));
			if(new Date().getTime() > token.exp - CONST_REFRESH_TIME) {
				return token;
			}
			return Promise.reject(true);
		}).then(refreshToken)
		.catch(function(error) {
			if(error == true) {
				return;
			}
			localStorage.removeItem('token');
			localStorage.removeItem('user');
		});
}

/**
 * 刷新token
 * 
 * @param token
 */
function refreshToken(token) {
	return axios({
		method: 'post',
		url: CONST_URL + '/oauth/token',
		params: {
			grant_type: 'refresh_token',
			refresh_token: token.refresh_token,
			scope: 'all'
		},
		auth: {
			username: CONST_CLIENT_ID,
			password: CONST_CLIENT_SECRET
		}
	}).then(function(response) {
		saveToken(response.data);
	}).catch(function(error) {
		alert('请重新登录！');
		console.log(error);
		throw error;
	});
}

/**
 * 登录。如果有异常，向外抛出，所以这里不捕获异常
 * 
 * @param username 用户名
 * @param password 密码
 */
function login(username, password, captcha) {
	return axios({
		method: 'post',
		url: CONST_URL + '/oauth/token',
		params: {
			grant_type: 'password',
			username: username,
			password: password,
			scope: 'all',
			captcha: captcha
		},
		auth: {
			username: CONST_CLIENT_ID,
			password: CONST_CLIENT_SECRET
		}
	}).then(function(response) {
		saveToken(response.data);
	});
}

/**
 * 将获取到的token处理后存入localStorage，并设置axios的请求头
 * 
 * @param token 
 */
function saveToken(token) {
	token.exp = new Date().getTime() + token.expires_in * 1000;
	localStorage.setItem('token', JSON.stringify(token));
	authAxios.defaults.headers.common['Authorization'] = token.token_type + ' ' + token.access_token;
}

/**
 * 通过authAxios中的token获取当前用户信息
 */
function getMe() {
	return authAxios({
		method: 'post',
		url: CONST_URL + '/user/me'
	}).then(function(response) {
		if(response.data.code == '0000') {
			var user = response.data.data;
			localStorage.setItem('user', JSON.stringify(user));
			return user;
		} else {
			console.log(response.data);
			return Promise.reject(response.data);
		}
	});
}

function isUsername(s) {
	return /^[\w\u4e00-\u9fa5]{2,20}$/g.test(s);
}

function isPassword(s) {
	return /^\w{6,16}$/g.test(s);
}

function isNickname(s) {
	return /^[\w\u4e00-\u9fa5]{2,20}$/g.test(s);
}

function isMobile(s) {
	return /^1[3-9]\d{9}$/g.test(s);
}

function isEmail(s) {
	return /^\w+@\w+(\.\w+)+$/g.test(s);
}

function isRoleName(s) {
	return /^\w{2,20}$/g.test(s);
}

function isRoleDescription(s) {
	return /^[\w\u4e00-\u9fa5]{2,20}$/g.test(s);
}

function isAuthorityName(s) {
	return /^\w{2,20}$/g.test(s);
}

function isAuthorityDescription(s) {
	return /^[\w\u4e00-\u9fa5]{2,20}$/g.test(s);
}

function isCaptcha(s) {
	return /^\w{5}$/g.test(s);
}

function isGroupName(s) {
	return /^[\w\u4e00-\u9fa5]{2,20}$/g.test(s);
}

// 从url上获取参数，并转换为对象
function getParams() {
	var params = location.search.substr(1).split('&');
	var res = {};
	for(var i = 0; i < params.length; i++) {
		var index = params[i].indexOf('=');
		var k = decodeURIComponent(params[i].substr(0, index));
		var v = decodeURIComponent(params[i].substr(index + 1));
		if(v == 'true') {
			v = true;
		}
		if(v == 'false') {
			v = false;
		}
		if(res[k] === undefined) {
			res[k] = v;
		} else {
			try {
				res[k].push(v);
			} catch(e) {
				res[k] = [res[k], v];
			}
		}
	}
	return res;
}

Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

Vue.filter('date', function(d, s) {
	if(!d) {
		return "";
	}
	return new Date(d).Format(s);
});

var checkTokenInterval = setInterval(checkToken, CONST_CHECK_TOKEN_TIME);